<template>
  <div class="departments" v-loading="loading">
    <el-card class="box-card">
      <!-- 第一行 -->
      <tree-tool :treeNode="company" :isRoot="true" @addDept="doAdd" />

      <el-divider></el-divider>

      <el-tree
        :data="data"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <!-- 把data传递给这个组件里的treeNode -->
        <tree-tool
          slot-scope="{ data }"
          :treeNode="data"
          @addDept="doAdd"
          @editDept="doEdit"
        />
      </el-tree>
      <addDepts
        ref="addDepts"
        :pid="currentId"
        :showDialog.sync="showDialog"
        @addDept="getDeptList"
      />
    </el-card>
  </div>
</template>


<script>
import treeTool from "./components/tree-tool";
import addDepts from "./components/add-depts";
import { getDepartments } from "@/api/departments";
import { transToTreeData } from "@/utils/transToTreeData";
export default {
  name: "components",
  components: {
    treeTool,
    addDepts,
  },

  data() {
    return {
      //加载动画
      loading: true,
      // 用来控制新增窗口的显示和隐藏
      showDialog: false,
      // 用来记录当前被点的id
      currentId: "",
      company: {
        name: "江苏传智播客教育科技股份有限公司",
        manager: "负责人",
      },
      // 绑定tree的默认显示文字和子节点
      defaultProps: {
        label: "name",
        children: "children",
      },
      data: [
        {
          id: 1,
          manager: "孙彩",
          name: "总裁办",
          children: [{ id: 11, name: "教学办", manager: "张三" }],
        },
        {
          id: "2",
          name: "行政部",
          manager: "罗通",
        },
        {
          id: "3",
          name: "人事部",
          manager: "李四",
        },
      ],
    };
  },
  created() {
    this.getDeptList();
  },
  //获取
  methods: {
    async getDeptList() {
      let res = await getDepartments();
      console.log(res);
      this.company.name = res.data.companyName;
      let list = res.data.depts;
      this.data = transToTreeData(list, "");
      this.loading = false;
    },

    doAdd(id) {
      console.log(id);
      this.showDialog = true;
      // 把被点的id赋值给currentId
      // 只要赋值给currentId,那么add-depts这个子组件就能收到这个id了
      this.currentId = id;
    },
    // 点击了查看部门触发
    async doEdit(id) {
      // 调用子组件里获取详情的方法
      await this.$refs.addDepts.getDetail(id);

      // 打开窗口
      this.showDialog = true;
    },
  },
};
</script>

<style>
.box-card {
  margin: 20px;
  padding: 140px 120px;
}
</style>